import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
import {
    remark
} from 'remark'
import html from 'remark-html'

const postsDirectory = path.join(process.cwd(), 'posts')

export function getSortedPostsData() {
    // Get file names under /posts
    const fileNames = fs.readdirSync(postsDirectory)
    const allPostsData = fileNames.map(fileName => {
        // Remove ".md" from file name to get id
        const id = fileName.replace(/\.md$/, '')

        // Read markdown file as string
        const fullPath = path.join(postsDirectory, fileName)
        const fileContents = fs.readFileSync(fullPath, 'utf8')

        // Use gray-matter to parse the post metadata section
        const matterResult = matter(fileContents)

        // Combine the data with the id
        return {
            id,
            ...matterResult.data
        }
    })
    // Sort posts by date
    return allPostsData.sort((a, b) => {
        if (a.date < b.date) {
            return 1
        } else {
            return -1
        }
    })
}

export function getAllPostIds() {
    const fileNames = fs.readdirSync(postsDirectory)

    // Returns an array that looks like this: [   {     params: {       id:
    // 'ssg-ssr'     }   },   {     params: {       id: 'pre-rendering'     }   } ]
    const obj = fileNames.map(fileName => {
        return {
            params: {
                id: fileName.replace(/\.md$/, '')
            }
        }
    })
    // console.log(obj);
    return obj
}

// 根据数据来自动生成动态路由的paths配置
// 如果是async函数返回值是一个promise
export function getAllMypageNames() {
    // 获取文件
    const getfill = path.join(process.cwd(), 'pages/json/data01.json')
    // 读取文件内容
    const getdata = JSON.parse(fs.readFileSync(getfill, 'utf-8'))
    // 返回生成的配置信息
    const obj = Object
        .keys(getdata)
        .map(ele => {
            return {
                params: {
                    pname: ele
                }
            }
        })
    // console.log(obj);
    return obj
}

export async function getPostData(id) {
    const fullPath = path.join(postsDirectory, `${id}.md`)
    const fileContents = fs.readFileSync(fullPath, 'utf8')

    // Use gray-matter to parse the post metadata section
    const matterResult = matter(fileContents)

    // Use remark to convert markdown into HTML string
    const processedContent = await remark()
        .use(html)
        .process(matterResult.content)
    const contentHtml = processedContent.toString()

    // Combine the data with the id and contentHtml
    return {
        id,
        contentHtml,
        ...matterResult.data
    }
}